import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 10,
    java: {
      name: 'java',
      count: 20
    },
    web: {
      name: 'web',
      count: 50
    },
    ui: {
      name: 'ui',
      count: 30
    },
    carts: [],
    collects: []
  },
  mutations: {
    //加法
    add(state, num) {
      console.log(num)
      state.count += num
    },
    vote(state, name) {
      name === 'java'
        ? state.java.count++
        : name === 'web'
        ? state.web.count++
        : state.ui.count++
    },
    cartPush(state, goods) {
      let index = state.carts.findIndex(v => v.id === goods.id)
      if (index === -1) {
        return state.carts.push(goods)
      }
      state.carts[index].num++
    },
    cartMove(state, goods) {
      let index = state.carts.findIndex(v => v.id === goods.id)
      state.carts.splice(index, 1)
    },
    collectsPush(state, goods) {
      let index = state.collects.findIndex(v => v.id === goods.id)
      if (index === -1) {
        state.collects.push(goods)
        Vue.prototype.$message.success('收藏成功')
        return
      }
      Vue.prototype.$message.info('已收藏')
    },
    collectsMove(state, goods) {
      let index = state.collects.findIndex(v => v.id === goods.id)
      state.collects.splice(index, 1)
    }
  },
  actions: {
    votes(context, num) {
      console.log(num)
      //context是上下文===store对象，commit是调用mutations中的函数add
      context.commit('add', num)
    }
  },
  modules: {},
  getters: {
    getSumVoteCount(state) {
      return state.java.count + state.web.count + state.ui.count
    },
    getCartList(state) {
      return state.carts
    }
  }
})
